#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-12-16

@author: Neo.Chen
'''

import os
import logging

file_handler = 0
formatter = ""

def init(strLogFileName):
    logging.basicConfig(level= logging.DEBUG, format = '%(asctime)s : %(levelname)-8s %(message)s', datefmt  = '%m-%d %H:%M');
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler();
    console.setLevel(logging.DEBUG);
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(asctime)s : %(levelname)-8s %(message)s');
    # tell the handler to use this format
    #console.setFormatter(formatter);
    #logging.getLogger('').addHandler(console);
     
    file_handler = logging.FileHandler(strLogFileName, "w")
    file_handler.setFormatter(formatter)
    logging.getLogger('').addHandler(file_handler)

    try:
        logging.info("This is logging example");
        logging.debug("you can see this line only in log file, not show on print output");
        logging.warning("you can see this line both in log file and on print output");
        logging.error("you can see this line both in log file and on print output"); 
    except:
        logging.exception("Unknown Error !");
        raise;
    
def change_log():
    #这里进行主动换log文件等处理
    file_handler.close()
    logging.getLogger('').removeHandler(file_handler)
    file_handler = logging.FileHandler(os.getcwd() + "/test.log", "w")
    file_handler.setFormatter(formatter)  
    logging.getLogger('').addHandler(file_handler)
    
def info(msg, *args, **kwargs):
    logging.info(msg, args, kwargs)
    
def debug(msg, *args, **kwargs):
    logging.debug(msg, args, kwargs)
    
def warning(msg, *args, **kwargs):
    logging.warning(msg, args, kwargs)

def error(msg, *args, **kwargs):
    logging.error(msg, args, kwargs)
    
    
if __name__ == '__main__':
    try:
        init("test.log")
        info("This is logging example");
        debug("you can see this line only in log file, not show on print output");
        warning("you can see this line both in log file and on print output");
        error("you can see this line both in log file and on print output"); 
    except:
        exception("Unknown Error !");
        raise;
    
